package cn.itlaobing.springbootdemo.web.controller;

import cn.itlaobing.springbootdemo.entity.SystemAccount;
import cn.itlaobing.springbootdemo.service.SystemAccountService;
import com.google.gson.Gson;
import com.qiniu.common.QiniuException;
import com.qiniu.common.Zone;
import com.qiniu.http.Response;
import com.qiniu.storage.Configuration;
import com.qiniu.storage.UploadManager;
import com.qiniu.storage.model.DefaultPutRet;
import com.qiniu.util.Auth;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.io.File;

@Controller
public class HomeController extends BaseController{

    @Autowired
    private SystemAccountService systemAccountService;

    @GetMapping("/")
    public String home(Model model){
        return "home";
    }


    @GetMapping("/changePwd")
    public String changePwd(){
        return "/profile/changePwd";
    }

    @PostMapping("/changePwd")
    public String changePwd(String oldPwd, String newPwd, String confirmPwd, Model model,
                            RedirectAttributes redirectAttributes){
        //获取当前用户
        SystemAccount systemAccount=getCurrentSystemAccount();

        boolean hasError=false;
        if(StringUtils.isBlank(oldPwd)){
            model.addAttribute("oldPwdError","旧密码不能为空");
            hasError=true;
        }
        if(StringUtils.isBlank(newPwd)){
            model.addAttribute("newPwdError","新密码不能为空");
            hasError=true;
        }
        if(!newPwd.equals(confirmPwd)){
            model.addAttribute("confirmPwdError","两次输入密码不一致");
            hasError=true;
        }
        if(hasError){
            return "/profile/changePwd";
        }
        if(systemAccountService.authentication(systemAccount.getAccount(),oldPwd)==null){
            model.addAttribute("oldPwdError","旧密码不正确");
            return "/profile/changePwd";
        }
        systemAccountService.chagePassword(systemAccount.getAccount(),newPwd);

        redirectAttributes.addFlashAttribute("message","密码修改成功!");
        return "redirect:/";
    }

    @GetMapping("/editInfo")
    public String editInfo(){
        return "/profile/editInfo";
    }

    @PostMapping("/uploadPic")
    @ResponseBody
    public String uploadPic(MultipartFile picHead){
      //  picHead就是从客户端上传到服务器的图片，现在需要将这个图片上传到七牛云
        String picHeadUrl=uploadToQiniu(picHead);
        //SystemAccount systemAccount=getCurrentSystemAccount();
        //systemAccount.setPicHead(picHeadUrl);
        //systemAccountService.updatePicHead(systemAccount);
        return picHeadUrl;  //重定向到个人中心
    }

    @PostMapping("/editInfo")
    public String editInfo(String picHeadUrl){
        SystemAccount systemAccount=getCurrentSystemAccount();
        systemAccount.setPicHead(picHeadUrl);
        systemAccountService.updatePicHead(systemAccount);
        return "redirect:/";

    }


    /**
     * 从yml文件中注入 七牛的配置
     */

    @Value("${qiniu.accessKey}")
    private String accessKey;
    @Value("${qiniu.secretKey}")
    private String secretKey;
    @Value("${qiniu.bucket}")
    private String bucket;
    @Value("${qiniu.domain}")
    private String domain;
    /**
     *
     * @param picHead
     * @return 七牛云图片的地址
     */
    private String uploadToQiniu(MultipartFile picHead){
        //构造一个带指定Zone对象的配置类 ，
        //  https://developer.qiniu.com/kodo/manual/1671/region-endpoint  区域配置
        Configuration cfg = new Configuration(Zone.zone0());
//...其他参数参考类注释
        UploadManager uploadManager = new UploadManager(cfg);

        try {
       // String localFilePath = "e:/123.jpg";
        byte[]  picFileBytes=picHead.getBytes();
//默认不指定key的情况下，以文件内容的hash值作为文件名
        String key = null;
        Auth auth = Auth.create(accessKey, secretKey);
        String upToken = auth.uploadToken(bucket);
            Response response = uploadManager.put(picFileBytes, key, upToken);
            //解析上传成功的结果
            DefaultPutRet putRet = new Gson().fromJson(response.bodyString(), DefaultPutRet.class);
            //图片上传后，图片的url= 骑牛存储空间域名/putRet.hash
            return "http://"+domain+"/"+putRet.hash;
        } catch (QiniuException ex) {
            Response r = ex.response;
            System.err.println(r.toString());
            try {
                System.err.println(r.bodyString());
            } catch (QiniuException ex2) {
                //ignore
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return "";
    }





}
